package com.javaDemo.designpattern.yewuceluemoshi;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * https://zhuanlan.zhihu.com/p/347389684
 * 权限校验服务类
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService, ApplicationContextAware, InitializingBean {
    private ApplicationContext applicationContext;
    //注：这里可以使用Map，偷个懒
    private List<PermissionCheckHandler> handlers = new ArrayList<>();
    @Override
    public PermissionCheckResultDTO permissionCheck(ArtemisSellerBizType artemisSellerBizType, Long userId, String bizCode) {
        //省略一些前置逻辑
        PermissionCheckHandler handler = getHandler(artemisSellerBizType);
        return handler.permissionCheck(userId, bizCode);
    }
    private PermissionCheckHandler getHandler(ArtemisSellerBizType artemisSellerBizType) {
        for (PermissionCheckHandler handler : handlers) {
            if (handler.isMatched(artemisSellerBizType)) {
                return handler;
            }
        }
        return null;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        for (PermissionCheckHandler handler : applicationContext.getBeansOfType(PermissionCheckHandler.class)
            .values()) {
            handlers.add(handler);
            log.warn("load permission check handler [{}]", handler.getClass().getName());
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}